package com.YKFuse.wrapper.calculate;

import lombok.Data;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yuank
 * @version 1.0.0
 * @date 2025/2/11 15:09:07
 *
 * 专属于一个需要熔断支持的Method的 计数情况
 *
 */
@Data
public class MethodCalculator {
    // volatile可见性  atomic可见性 +原子性
    private AtomicInteger success;
    private AtomicInteger error;
    // 注解指定
    private double fuseRate;
    private long resetTimeWindows;
    // yml指定 熔断重试
    private int retry;
    private long nextTryTime;

    public MethodCalculator(double fuseRate) {
        this.fuseRate = fuseRate;
    }


    public void error() {
        error.incrementAndGet();
    }
    public void success() {
        success.incrementAndGet();
    }

    public void reset() {
        success= new AtomicInteger(0);
        success= new AtomicInteger(0);
    }


    public boolean fuseCheck() {
        int errorCount = error.get();  // 获取错误次数
        int successCount = success.get();  // 获取成功次数
        double failureRate = (errorCount + successCount) == 0 ? 0 : (double) errorCount / (errorCount + successCount);
        return failureRate > fuseRate;  // 判断失败率是否超过熔断阈值
    }

}